<template>
    <el-form 
        ref="myform" 
        :model="form" 
        label-width="80px"
        status-icon 
        class="myform"
        :rules="rules"
      >
      <el-form-item label="账号" prop="phone" >
        <el-input 
        prefix-icon="el-icon-user" 
        v-model="form.phone"
         placeholder="请输入账号(手机号或者用户名)"
         autocomplete="off"
         type="text"
      ></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password" >
        <el-input 
        prefix-icon="el-icon-lock" 
        v-model="form.password"
        type="password"
         placeholder="请输入密码"
         autocomplete="off"
         show-password
      ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" block  @click="todoLogin" :loading="loading">登录</el-button>
        <el-button type="info" block @click="resetData">重置</el-button>
      </el-form-item>
    </el-form>
</template>

<script>
import {ref,reactive,toRefs ,onMounted,watch ,onBeforeUpdate  } from "vue"
import { reg } from '../../utils/validate';
import { toast } from '../../utils';
import {useStore} from 'vuex'
import { ajax } from '../../service';
import {useRouter} from "vue-router"
export default {
  name:"logincom",
  props:['phone'],
  setup(props,context){  // props 对应就是组件的props 
    const myform = ref()
    const store = useStore();
    const router = useRouter()
    const state = reactive({
      loading:false,
      form:{
        
      },
      rules:{
        phone:[
          {
            required: true, message: '请输入账号', trigger: 'blur'
          }
        ],
        password:[
           {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            pattern:reg.pwd, message: '请输入6-16位数字和字母组合', trigger: 'blur'
          }
        ]
      }
    })
    onMounted(()=>{
       state.form.phone = localStorage.getItem("account")
    })

    onBeforeUpdate(()=>{
       state.form.phone = props.phone;
    })  

    const todoLogin = ()=>{
        // 登录逻辑 
        myform.value.validate(async valid=>{
           if(valid){
              // 走登录的接口 
             const {code,result,token} = await  ajax.login(state.form);
             if(code==200){
                router.push({name:"main"})
                localStorage.setItem("account",state.form.phone);
                sessionStorage.setItem("authtoken",token)
             }
             
           }else{
             toast.showError("请输入有效的登录信息")
           }
        })
    }
    const resetData = ()=>{
        myform.value.resetFields()
    }
    return {
      myform,
      ...toRefs(state),
      todoLogin,
      resetData
    }
  }
}
</script>
